package com.sylar.happyreader;

import java.util.List;
import java.util.concurrent.Callable;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.sylar.happyreader.bean.BookItem;
import com.sylar.happyreader.db.Crud;
import com.sylar.happyreader.listener.Callback;
import com.sylar.happyreader.net.HttpTool;
import com.sylar.happyreader.tools.Config;
import com.sylar.happyreader.tools.TaskUtils;
import com.sylar.happyreader.tools.Utils;
import com.sylar.happyreader.view.BookViewHolder;
import com.sylar.happyreader.view.FastBitmapDrawable;
import com.sylar.happyreader.view.ShelvesView;

public class BookHisoryActivity extends Activity implements OnItemClickListener, Callable<String>, Callback<String> {

	private ShelvesView mGrid;
	private ImageView titleImage;

	private RelativeLayout mainLayout;

	private Crud crud;

	private List<BookItem> book_hisory;
	
	private BookItem cache_book;

	private static final int MSG_GET_BOOKPAGELISTS = 300;

	private static int TASK_TYPE;
	private static final int CHANGE_BOOKLISTS = 1;
	private static final int GET_BOOKPAGELISTS = CHANGE_BOOKLISTS + 1;

	private String style = "";
	private String sex = "man";
	private String bookName;
	
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case MSG_GET_BOOKPAGELISTS:
				TASK_TYPE = GET_BOOKPAGELISTS;
				cache_book = (BookItem) msg.obj;
				TaskUtils.doAsync(BookHisoryActivity.this, null, "正在加载中哦..", BookHisoryActivity.this, BookHisoryActivity.this);
				break;
			}

		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

		setContentView(R.layout.bookhisoryview);

		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);

//		titleImage = (ImageView) findViewById(R.id.titleImage);
//		titleImage.setVisibility(View.VISIBLE);
//
//		mainLayout = (RelativeLayout) findViewById(R.id.MainLayout);
//
//		mGrid = (ShelvesView) findViewById(R.id.grid_shelves);
//		mGrid.setFastScrollEnabled(true);
//		mGrid.setOnItemClickListener(this);
//		
//		crud = new Crud(this);
//		TaskUtils.doAsync(this, null, "正在加载中哦..", this, this);
		
		LoadHistory();
		
//		if (RegisterWeiBo()) {
//			LoadHistory();
//		}
//		else {
//	    	m_timer = new Timer();
//	    	m_timerHandle = new Handler(){  
//	        	public void handleMessage(Message msg) {
//	                switch (msg.what) {      
//	                case 1:
//	                	if (0 == CheckLoginState()) {
//	                		//DoNothing
//	                	}
//	                	else if (1 == CheckLoginState()) {
//	                		//Quit
//	                		Toast.makeText(BookHisoryActivity.this, "亲，登陆失败了！", Toast.LENGTH_SHORT).show();
//	                		m_timer.cancel();
//	                		finish();
//	                	}
//	                	else if (2 == CheckLoginState()) {
//	                		m_timer.cancel();
//	                		LoadHistory();
//	                	}
//	                }
//	        	}
//	    	};
//	        TimerTask task = new TimerTask(){  
//	            public void run() {  
//	                Message message = new Message();      
//	                message.what = 1;      
//	                m_timerHandle.sendMessage(message);    
//	            }};         
//	        m_timer.schedule(task, 500, 500); 			
//		}
		
	}
	
	@Override
	protected void onResume() {
		
		super.onResume();
	}

	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if(book_hisory==null) return;
		Message msg = handler.obtainMessage(MSG_GET_BOOKPAGELISTS);
		msg.obj = book_hisory.get(position);
		handler.sendMessage(msg);
	}

	public void onCallback(String pCallbackValue) {
		if(TASK_TYPE == GET_BOOKPAGELISTS){
			if ("ok".equals(pCallbackValue)) {
//				//TODO发微博
//				MainActivity.SetBookName(BookHisoryActivity.this, bookName);
//				MainActivity.SendWeiBo(BookHisoryActivity.this,new WeiBoSendBack() {
//					
//					public void OnWeiBoSend() {
//						Intent intent = new Intent(BookHisoryActivity.this, ReadBookPagesActivity.class);
//						intent.putExtra("style", style);
//						intent.putExtra("sex", sex);
//						intent.putExtra("bookName", bookName);
//						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						BookHisoryActivity.this.startActivity(intent);
//					}
//				});

				Intent intent = new Intent(BookHisoryActivity.this, BookPagesActivity.class);
				intent.putExtra("style", style);
				intent.putExtra("sex", sex);
				intent.putExtra("bookName", bookName);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				BookHisoryActivity.this.startActivity(intent);
			
			} else {
				Toast.makeText(this, "加载失败了哦", 1).show();
			}
			TASK_TYPE = -1;
		}else{
			if (pCallbackValue.equals("ok"))
				mGrid.setAdapter(new BookAdapter(this, book_hisory, mGrid));
		}
		
	}
	
	
	public String call() throws Exception {
		String result = "";
		if(TASK_TYPE == GET_BOOKPAGELISTS){
			if(cache_book==null) return "error";
			
			String url = Config.RequestUri + "sex=" + cache_book.getSex() + "&style=" + Uri.encode(cache_book.getStyle()) + "&bookName=" + Uri.encode(cache_book.getBookname());
			String httpResult = HttpTool.getString(getApplicationContext(),url);
			if (httpResult != null && !"".equals(httpResult)) {
				sex = cache_book.getSex();
				style = cache_book.getStyle();
				bookName = cache_book.getBookname();
				Config.pagelists = Utils.SubArray(httpResult.split(".txt"));
				result = "ok";
			} else {
				result = "error";
			}
			
		}else{
			if (crud != null) {
				book_hisory = crud.getBookHisoryList();
				if (book_hisory != null)
					result = "ok";
			}
		}
		
		return result;
	}

	class BookAdapter extends BaseAdapter {
		private Activity mActivity;
		private final Bitmap mDefaultCoverBitmap;
		private final FastBitmapDrawable mDefaultCover;

		private ShelvesView mShelvesView;
		private List<BookItem> mBooks;

		public BookAdapter(Activity activity, List<BookItem> books, ShelvesView listView) {
			super();
			this.mActivity = activity;
			this.mShelvesView = listView;
			this.mBooks = books;
			mDefaultCoverBitmap = BitmapFactory.decodeResource(mActivity.getResources(), R.drawable.default_book_cover);
			mDefaultCover = new FastBitmapDrawable(mDefaultCoverBitmap);
		}

		public int getCount() {
			return mBooks.size();
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			BookViewHolder holder = null;
			if (convertView == null) {
				convertView = BookHisoryActivity.this.getLayoutInflater().inflate(R.layout.text_row, parent, false);
				holder = new BookViewHolder(convertView);
				convertView.setTag(holder);
			} else {
				holder = (BookViewHolder) convertView.getTag();
			}
			String coverPath = Config.CoverUri + mBooks.get(position).getSex() + "/" + Uri.encode(mBooks.get(position).getStyle()) + "/" + Uri.encode(mBooks.get(position).getBookname()) + "/"
					+ Uri.encode(mBooks.get(position).getBookname()) + ".jpg";

//			final ImageView titleText = holder.getImage();
//			BubbleTextView text1 = holder.getTitle();
//			titleText.setTag(coverPath);

//			Drawable cachedImage = asyncImageLoader.loadDrawable(coverPath, new ImageCallback() {
//				public void imageLoaded(Drawable imageDrawable, String imageUrl) {
//					ImageView imageViewByTag = (ImageView) mShelvesView.findViewWithTag(imageUrl);
//					if (imageViewByTag != null) {
//						titleText.setImageDrawable(imageDrawable);
//					}
//				}
//			});
//			if (cachedImage == null) {
//				titleText.setImageDrawable(mDefaultCover);
//			} else {
//				titleText.setImageDrawable(cachedImage);
//			}
//			text1.setText(mBooks.get(position).getBookname());
			return convertView;
		}

	}
	
	
	protected void LoadHistory() {
//		titleImage = (ImageView) findViewById(R.id.titleImage);
//		titleImage.setVisibility(View.VISIBLE);

		mainLayout = (RelativeLayout) findViewById(R.id.MainLayout);

		mGrid = (ShelvesView) findViewById(R.id.grid_shelves);
		mGrid.setFastScrollEnabled(true);
		mGrid.setOnItemClickListener(this);

		crud = new Crud(this);

		TaskUtils.doAsync(this, null, "正在加载中哦..", this, this);		
	}
	
}
